package com.eicas.config;

import com.eicas.Constant;
import com.eicas.JwtTokenManager;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author: Administrator
 * @since: 2023/2/9 11:57
 * @description:
 */
@Configuration
public class JwtFilter implements GlobalFilter, Ordered {
    @Autowired
    private JwtTokenManager jwtTokenManager;
    private static final String USERNAME = "username";
    @Value("${ignore.whites.login}")
    private String whites;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //向header 中添加 gateway key
        ServerHttpRequest build = exchange.getRequest().mutate().header(Constant.GATEWAY_KEY, Constant.SET_VALUE).build();
        exchange = exchange.mutate().request(build).build();

        String path = exchange.getRequest().getPath().value();
        if (path.contains(whites)) {
            return chain.filter(exchange);
        }
        HttpHeaders headers = exchange.getRequest().getHeaders();
        String token = headers.getFirst(Constant.AUTHORIZATION_HEADER);
        ServerHttpResponse response = exchange.getResponse();
        if (StringUtils.isEmpty(token)) {
            //需要进行用户登录
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        jwtTokenManager.validateToken(token);
        response.setStatusCode(HttpStatus.OK);
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
